package servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author andrei costache
 *
 */
public class ContentListViewController extends ContentController {

	@Override
	public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
            RequestDispatcher view = null;
            String order_submitted = request.getParameter("submit_filter");
            String order_by = request.getParameter("order_by");
            String order_type = request.getParameter("order_type");
            if (order_submitted != null){
                String redirect = "/content/list?";
                if (order_by != null && !order_by.trim().equals("")){
                    redirect += "order_by="+order_by;
                    if (order_type != null && !order_type.trim().equals("")){
                        redirect += "&order_type="+order_type;
                    }
                }
                response.sendRedirect(request.getContextPath()+redirect);
            } else {
                String page = request.getParameter("page");
                if (page == null){
                    page = "1";
                }
                Integer pg = new Integer(page);
                int[] range = new int[2];
                range[1] = pg * 10 - 1;
                range[0] = range[1] - 9;
                //will display only 10 results per page
                request.setAttribute("contentList", contentDAO.findRange(range, order_by, order_type));
                //request.setAttribute("contentList", contentDAO.findRange(range));
                request.setAttribute("total_pages", contentDAO.count()/10+1);
                request.setAttribute("current_page", pg);
                request.setAttribute("active_servlet_path", "/content/list");
                view = request.getRequestDispatcher("/jsp/ContentListView.jsp");
                view.forward(request, response);
            }

	}
}
